package org.nowcoder.leetcode.linkedList;

/**
 * Title  : 92. Reverse Linked List II
 * Source : https://leetcode.cn/problems/reverse-linked-list-ii/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-13
 */

public class LeetCode_92 {
    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        //1. 将[left,right]数据复制出来，反转，再放回到list
        if (head.next == null || left == right) {
            return head;
        }
        int[] elements = new int[right - left + 1];
        ListNode leftNode = null, p = head;
        int count = 1, i = 0;
        while (p != null) {
            if (left <= count && count <= right) {
                if (count == left) {
                    leftNode = p;
                }
                elements[i++] = p.val;
            }
            count++;
            if (count > right) break;
            p = p.next;
        }
        for (int k = i - 1; k >= 0; k--) {
            leftNode.val = elements[k];
            leftNode = leftNode.next;
        }
        return head;
    }
}
